import express = require('express');
import { app } from '../app';
import { RequestObject, createError, ErrorStatus } from '../public/common/common';
import { BaseService } from '../server/mongo';

export let remote = express.Router();
remote.get('/', function (req, res, next) {
    res.send('API 请求');
});
remote.post('/remoteCall', function (req, res, next) {
    // let service = app.locals['service'];
    let buffer = [];
    req.on('data', function (chuck) {
        buffer.push(chuck);
    });

    req.on('end', function () {
        try {
            let post = Buffer.concat(buffer);
            let requestString = post.toString('utf8');
            let requestObj = JSON.parse(requestString) as RequestObject;
            let services = app.locals['services'];
            if (services) {
                let service = services[requestObj.service] as BaseService;
                if (!service) throw createError(ErrorStatus.ERROR_SERVICE_NOT_FOUND, '服务不存在');
                service.call(
                    req.session.token || undefined,
                    requestObj.functionName,
                    requestObj.args).then(result => {
                        let response = JSON.stringify({
                            d: result
                        });
                        res.send(response);
                    }).catch(error => {
                        res.status(error.status || 500).send(error.message);
                    });
            }
        } catch (error) {
            res.status(error.status || 500).send(error.message);
        }
    });
});